//
//  GroupCell.swift
//  DSP
//
//  Created by tucici on 2024/5/16.
//

import UIKit
import TCCKit

protocol GroupCellDelegate{
    func select(_ group: GroupModel, _ index:Int)
}

class GroupCell: UITableViewCell {
    private var collectionView : UICollectionView!
    var ignoredEnable : Bool = false
    var delegate : GroupCellDelegate?
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        initUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func initUI(){
        backgroundColor = .clear
        selectionStyle = .none
        
        let flowlayout = UICollectionViewFlowLayout()
        flowlayout.scrollDirection = .vertical
        flowlayout.minimumLineSpacing = 10.0.k_w
        flowlayout.minimumInteritemSpacing = 10.0
        flowlayout.sectionInset = UIEdgeInsets(top: 9.k_h, left: 10.k_w, bottom: 9.k_h, right: 10.k_w)
        collectionView = UICollectionView(frame:.zero,collectionViewLayout:flowlayout)
        collectionView.backgroundColor = .clear
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.showsVerticalScrollIndicator = false
        collectionView.register(CHItem.self, forCellWithReuseIdentifier:CHItem.ID())
        
        contentView.addSubview(collectionView)
        
        collectionView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.height.equalTo(0)
        }
    }
    
    var array = [GroupModel](){
        didSet{
            guard let flowlayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout else{ return}
            let row = ceil(Double(array.count) / 4.0)
            let w = row > 1 ? 32.k_h : 40.k_h
            let h = w * row + flowlayout.minimumLineSpacing * (row - 1.0) + flowlayout.sectionInset.top + flowlayout.sectionInset.bottom
            collectionView.reloadData()
            collectionView.snp.updateConstraints { make in
                make.height.equalTo(floor(h))
            }
        }
    }
    
    private func delectAction(_ group: GroupModel, _ index:Int){
        for ch in APP.CHM.array{
            if group.select == false{continue}
            ch.select = group.contain(ch: ch)
        }
        ///如果group是取消，且所有通道的都未选中，则取group的ch1为选中状态
        if group.select == false && APP.CHM.select_ch.name == "" {
            group.ch1.select = true
        }
        delegate?.select(group, index)
    }
}

//MARK: - UICollectionViewDataSource
extension GroupCell:UICollectionViewDataSource{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return array.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier:CHItem.ID(), for:indexPath) as! CHItem
        let group = array[indexPath.row]
        cell.title.text = group.name
        cell.title.borderWidth = 1
        cell.title.cornerRadius = 4.k_h
        cell.title.minimumScaleFactor = 0.8
        cell.title.adjustsFontSizeToFitWidth = true
        if group.enable == false && ignoredEnable == false{
            cell.title.textHexColor = HEX_TEXT_DISABLE
            cell.title.bgHexColor = HEX_BG_DISABLE
            cell.title.borderHexColor = HEX_BORDER_DISABLE
        }else{
            cell.title.textHexColor = (group.select ? HEX_BLACK : HEX_WHITE)
            cell.title.bgHexColor = (group.select ? HEX_RED : HEX_BG)
            cell.title.borderHexColor = (group.select ? HEX_RED : HEX_BLACK)
        }
        ///这里特别处理RESET EQ 长按2秒
        cell.longpress.minimumPressDuration = group.name == "Reset EQ" ? 2 : 0.5
        cell.block = {[weak self] in
            ///group数组，
            if group.chArr.count > 0 {
                group.select = false
                ///如果这时候，没有任何选中的通道，则设置group的ch1通道是选中状态
                if APP.CHM.array.first(where: { $0.select }) == nil{
                    group.ch1.select = true
                }
            }
            ///这里特别处理，Reset EQ 也包含在内，可以通过长按手势
            else if group.name == "Reset EQ" {
            }
            self?.delectAction(group, indexPath.row)
        }
        return cell
    }
}
//MARK: - UICollectionViewDelegate
extension GroupCell:UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){
        let group = array[indexPath.row]
        if group.enable == false && ignoredEnable == false {return}
        
        if group.chArr.count > 0 {
            if group.select {return}
            let vc = ChooseController()
            vc.group = group
            currentVC().present(vc, animated: false)
            vc.block = {[weak self] select_ch in
                group.select = true
                group.ch1 = group.chArr.filter{$0.num == select_ch.num}.first ?? ChannelModel()
                self?.delectAction(group, indexPath.row)
            }
        }
        ///因为Reset EQ 走长按手势了，这里就屏蔽点击
        else if group.name != "Reset EQ"{
            delegate?.select(group, indexPath.row)
        }
    }
}

//MARK: - UICollectionViewDelegateFlowLayout
extension GroupCell:UICollectionViewDelegateFlowLayout
{
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize{
        guard let flow = collectionView.collectionViewLayout as? UICollectionViewFlowLayout else{ return .zero}
        let num = (indexPath.row < 3 && array.count > 4) ? 3.0 : 4.0
        let h =  array.count > 4 ? 32.k_h : 40.k_h
        let w = (kUIScreenWidth - flow.sectionInset.left - flow.sectionInset.right - flow.minimumInteritemSpacing * (num - 1.0)) / num
        return CGSize(width: floor(w), height: floor(h))
    }
}


